//
//  CJSSearchViewController.m
//  GoTraveling
//
//  Created by 陈金山 on 15/12/30.
//  Copyright © 2015年 开发华佗. All rights reserved.
//

#import "CJSSearchViewController.h"
#import "Resources.h"
#import "CJSSearch.h"
#import "CJSSearchCell.h"
#import "CJSTravelNotesViewController.h"
#import "MJRefresh.h"
#import "MBProgressHUD.h"


#define kISFIRST 120
#define kISNOTFIRST 60

@interface CJSSearchViewController ()<UITextFieldDelegate, UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, retain) UITextField *search;

@property (nonatomic, retain) UIButton *cancel;

@property (nonatomic, retain) UITableView *tableView;

@property (nonatomic, retain) NSMutableArray *resultArray;

@property (nonatomic, assign) NSInteger num;

@property (nonatomic, retain) MBProgressHUD *mbBarPrpgressV;

@property (nonatomic, retain) NSString *lightString;

@end

@implementation CJSSearchViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.resultArray = [NSMutableArray array];
    self.num = 0;
    
    //返回按钮
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"icon_nav_back_button"] style:UIBarButtonItemStylePlain target:self action:@selector(leftAction:)];
    self.navigationItem.leftBarButtonItem.tintColor = [UIColor whiteColor];
    
    //搜索栏
    UIView *iconView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
    UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"SearchBarButton"]];
    imageView.frame = CGRectMake(5, 5, 20, 20);
    [iconView addSubview:imageView];
    
    self.search = [[UITextField alloc] initWithFrame:CGRectMake(50, 6, SCREEN_WIDTH - kISFIRST, 30)];
    self.search.leftView = iconView;
    self.search.tintColor = [UIColor whiteColor];
    self.search.leftViewMode = UITextFieldViewModeAlways;
    self.search.placeholder = @" 搜索游记、故事集";
    self.search.delegate = self;
    self.search.textColor = [UIColor whiteColor];
    self.search.backgroundColor = [UIColor grayColor];
    self.search.layer.cornerRadius = 5;
    self.search.layer.masksToBounds = YES;
    self.search.clearsOnBeginEditing = YES;
    self.search.keyboardType = UIKeyboardTypeWebSearch;
    [self.navigationController.navigationBar addSubview:self.search];
    
    [self.search becomeFirstResponder];
    
    self.cancel = [UIButton buttonWithType:UIButtonTypeCustom];
    self.cancel.frame = CGRectMake(SCREEN_WIDTH - kISNOTFIRST, 6, 50, 30);
    [self.cancel setTitle:@"取消" forState:UIControlStateNormal];
    [self.cancel setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.cancel addTarget:self action:@selector(cancelAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.navigationController.navigationBar addSubview:self.cancel];
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 64)];
    self.tableView.backgroundColor = self.view.backgroundColor;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.tableView registerClass:[CJSSearchCell class] forCellReuseIdentifier:@"searchCell"];
    [self.view addSubview:self.tableView];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.resultArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return 160;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    CJSSearchCell *cell = [tableView dequeueReusableCellWithIdentifier:@"searchCell"];
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    cell.lightString = self.lightString;
    cell.search = [self.resultArray objectAtIndex:indexPath.row];
    cell.contentView.backgroundColor = self.view.backgroundColor;
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [self.search resignFirstResponder];
    CJSTravelNotesViewController *travelNVC = [[CJSTravelNotesViewController alloc] init];
    travelNVC.spot_id = [[self.resultArray objectAtIndex:indexPath.row] Id];
    [self.navigationController pushViewController:travelNVC animated:YES];
}

#pragma mark - 取消按钮
- (void)cancelAction:(UIButton *)button {
    
    self.search.text = @"";
    [self.search resignFirstResponder];
    
    CGRect frame =  self.search.frame;
    frame.size.width = SCREEN_WIDTH - kISNOTFIRST;
    self.search.frame = frame;
    
    self.resultArray = [NSMutableArray array];
    [self.tableView reloadData];
    button.hidden = YES;
}

- (void)textFieldDidBeginEditing:(UITextField *)textField {
    
    CGRect frame =  textField.frame;
    frame.size.width = SCREEN_WIDTH - kISFIRST;
    textField.frame = frame;
    
    self.cancel.hidden = NO;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    
    self.num = 0;
    self.mbBarPrpgressV = [MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];
    [self.mbBarPrpgressV show:YES];
    self.lightString = textField.text;
    NSString * encodingString = [textField.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [self AFNWorkingWithUrl:encodingString start:0];
    self.num += 20;
    [textField resignFirstResponder];
    
    
    self.tableView.mj_footer = [MJRefreshAutoFooter footerWithRefreshingBlock:^{
        
        self.num += 20;
    }];
    
    return YES;
}

- (void)viewWillDisappear:(BOOL)animated {
    
    self.search.hidden = YES;
    self.cancel.hidden = YES;
}

- (void)viewWillAppear:(BOOL)animated {
    
    self.search.hidden = NO;
    self.cancel.hidden = NO;
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    
    CGRect frame = self.search.frame;
    frame.size.width = SCREEN_WIDTH - kISNOTFIRST;
    self.search.frame = frame;
    [self.search resignFirstResponder];
    self.cancel.hidden = YES;
}

#pragma mark - 返回
- (void)leftAction:(UIBarButtonItem *)bar {
    
    [self.search resignFirstResponder];
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - 网络请求
- (void)AFNWorkingWithUrl:(NSString *)urlString start:(NSInteger)start {
    
    if (start == 0) {
        self.resultArray = [NSMutableArray array];
    }
    
    NSString *strUrl = [NSString stringWithFormat:@"http://api.breadtrip.com/v2/search/?count=20&data_type=trip&key=%@&start=%ld", urlString, start];
    
    [Resources getDataWithName:strUrl block:^(id result) {
        
        NSDictionary *bigDic = [result objectForKey:@"data"];
        for (NSDictionary *dic in [bigDic objectForKey:@"trips"]) {
            CJSSearch *search = [[CJSSearch alloc] init];
            [search setValuesForKeysWithDictionary:dic];
            [self.resultArray addObject:search];
        }
        
        [self.mbBarPrpgressV hide:YES];
        [self.tableView reloadData];
    } error:^{
        
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"网络连接错误" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self.mbBarPrpgressV hide:YES];
        }];
        [alert addAction:action];
        
        [self presentViewController:alert animated:YES completion:nil];
    }];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
